#include "standard/nfile.h"
#include "standard/ntime.h"
#include "standard/nstring.h"
#include "dameon.h"
#include "processlog.h"

FILE           *file_open_log;

int ReadFile(std::string &s, const char* filename)
{
    std::ifstream readf;      
    
    readf.open(filename, std::ios::in);
    load_file(s, readf);
    
    readf.close();
    
    return 0;
}


int WriteLog(const char *buf, const char *filename, const char *method)
{
    return WriteLog(buf, filename, method, false);
}

int WriteLog(const char *buf, const char *filename, const char *method, bool show_time)
{
    int fd ,len;
        
    len = strlen(buf);    
    if (strncmp(method, "O_TRUNC", strlen(method)) == 0) {
        if ((fd=open(filename, O_CREAT|O_WRONLY|O_TRUNC,0600))<0) {
	        perror("open");
	        exit(1);
	    }
    }
    else {
        if ((fd=open(filename, O_CREAT|O_WRONLY|O_APPEND,0600))<0) {
	        perror("open");
	        exit(1);
	    }
	}
	
	int write_len = 0;
    if (show_time) {
        char str[80];	
        
        memset(str, 0, sizeof(str));
	    data(str);		
	    std::string data_str(str);
	    data_str += " : "; 
	    
	    write_len = write(fd, data_str.c_str(), data_str.length());
	    if (write_len != data_str.length()) {
	        // have error
	    }
	}
	  
    write_len = write(fd, buf, len);	
    if (write_len != len) {
        // have error
    }
	close(fd);
	  
    return 0;
}


int WriteLogT(const char *buf)
{
    return WriteLog(buf, "/tmp/dameon.log", "O_TRUNC");   
}

int WriteLogE(const char *buf)
{
    return WriteLog(buf, "/tmp/dameon.log", "O_APPEND");   
}

int WriteLog(const char *buf)
{
    return WriteLogE(buf);
}

int WriteLogTime(const char *buf)
{
    return WriteLog(buf, "/tmp/dameon.log", "O_APPEND", true);   
}

int WriteLogLoc(const char *buf, const char *filename, int line, const char *func)
{
    int fd ,len;
	int write_len = 0;    
    std::string s;
    	
    len = strlen(buf);
            
    if ((fd=open("/tmp/dameon.log", O_CREAT|O_WRONLY|O_APPEND,0600))<0) {
        perror("open");
        exit(1);
    }
	
	write_len = write(fd, " filename:", 10);	
	write_len = write(fd, filename, strlen(filename));  		
	std::string line_s = " line:" + itos(line);
	write_len = write(fd, line_s.c_str(), line_s.length());
	write_len = write(fd, " func:", 6);
	write_len = write(fd, func, strlen(func));
	write_len = write(fd, " ", 1);	
    write_len = write(fd, buf, len);
    write_len = write(fd, "\n", 1);
    
	close(fd);	  
    return 0;
}

void notice_msg(const char* msg)
{   
    std::cout<<"NOTICE: "<<msg<<"\n";
}

void ok_msg(const char* msg)
{   
    std::cout<<msg<<" OK!"<<"\n";
}

